<template>
  <div v-loading="loading" class="container">
    <div class="app-container">
      <el-tree :props="defaultProps" :data="depts" default-expand-all :expand-on-click-node="false">
        <template v-slot="{data}">
          <el-row type="flex" style="width: 100%; height: 40px;" align="middle">
            <el-col>{{ data.name }}</el-col>
            <el-col>
              <!-- <el-col :span="2"> -->
              <el-row type="flex" justify="end">
                <span class="username">{{ data.managerName }}</span>
                <el-dropdown @command="operateDept($event, data.id)">
                  <span class="username">
                    操作<i class="el-icon-arrow-down" />
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="add">添加子项目</el-dropdown-item>
                    <el-dropdown-item command="edit">编辑项目</el-dropdown-item>
                    <el-dropdown-item command="del">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <AddDept ref="addDept" :show-dialog.sync="showDialog" :current-id="currentId" @updateDept="getDepartment" />
  </div>
</template>
<script>
import { delDeparmentApi, getDepartmentApi } from '@/api'
import { transformListToTreeData } from '@/utils'
import { AddDept } from './components'
export default {
  name: 'Department',
  components: {
    AddDept
  },
  data() {
    return {
      depts: [],
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      showDialog: false,
      currentId: null,
      loading: false
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    async getDepartment() {
      this.loading = true
      this.depts = transformListToTreeData(await getDepartmentApi(), 0)
      this.loading = false
    },
    async operateDept(type, id) {
      if (type === 'add') {
        this.showDialog = true
        this.currentId = id
      } else if (type === 'edit') {
        this.currentId = id
        // 直接用async await传id，使用微任务宏任务可以使用currentId
        // this.$refs.addDept获取的是add-dept这个组件实例，代表this
        // 微任务 $nextTick
        this.$nextTick(async() => {
          await this.$refs.addDept.getDepartmentDetail()
          this.showDialog = true
        })

        // 宏任务
        // setTimeout(() => {
        //   this.$refs.addDept.getDepartmentDetail()
        // }, 0)

        // await this.$refs.addDept.getDepartmentDetail(id)
        // this.showDialog = true
      } else {
        // 删除
        await this.$confirm('确认要删除该部门吗') // promise
        await delDeparmentApi(id)
        this.$message.success('删除部门成功')
        this.getDepartment()
      }
    }
  }
}
</script>
<style scoped>
  .app-container {
    padding: 30px 150px;
  }
  .username {
    font-size: 14px;
    margin-right: 20px;
  }
</style>
